<template>
	<view>
		<custom-nav :title="form.formName"></custom-nav>

		<diy-navTab
			:activeTab="active"
			:tabList="tabList"
			@change="changeTab"
		></diy-navTab>

		<view class="container" @touchmove.prevent>
			<view v-if="active === 1 && !processType">
				<view class="pb160" style="padding-top: 0">
					<associate-form
						v-if="isAssociateFormMode"
						:title="associateFormTitle"
						:data="associateFormData"
					/>

					<form-render
						v-if="!loading"
						mode="MOBILE"
						ref="form"
						:forms="forms"
						:value="formData"
						@inputFormValue="getFormValue($event)"
						@setSingure="setSingure($event)"
						:isClickSumbit="isClickSumbit"
					/>

					<view v-if="instanceData">
						<processProgress
							:result="instanceData.result"
							:progress="instanceData.progress"
							:processList="processList"
							:title="'流程'"
						/>
					</view>

					<view v-else>
						<process
							:process="process"
							:dept-id="userDeptId"
							:pc-mode="false"
							:value="processUsers"
							v-if="!loading"
							:forms="forms"
							:formData="formData"
						></process>
					</view>
				</view>

				<view class="bottom-button-bd"
					><button
						:loading="loadingSumbit"
						class="primary-button w90"
						@tap.stop="$noMultipleClicks(sumbit, {})"
					>
						提交
					</button></view
				>
			</view>

			<view v-if="active == 2">
				<view class="data-container">
					<view
						v-show="dataList && dataList.length > 0"
						v-for="(dataItem, index) in dataList"
						:key="index"
						class="item-container"
					>
						<approve-item
							:data="dataItem"
							:active="2"
						></approve-item>
					</view>

					<diy-empty
						v-if="!dataList || dataList.length === 0"
					></diy-empty>
				</view>
			</view>

			<!--签名-->

			<uni-popup
				ref="signature"
				@maskClick="closeSignature()"
				catchtouchmove="true"
			>
				<view class="popup-bd">
					<view class="popup-title bd-bottom-e">
						请签字

						<uni-icons
							type="closeempty"
							size="40rpx"
							color="#666666"
							class="popup-close"
							@click="closeSignature()"
						></uni-icons>
					</view>

					<view class="popup-content" style="max-height: auto">
						<view
							v-if="isShowSignature"
							style="height: 100%; background: #fff"
						>
							<l-signature
								disableScroll
								backgroundColor="#fff"
								ref="signatureRef"
								:penColor="penColor"
								:penSize="penSize"
								:openSmooth="openSmooth"
								landscape="true"
							></l-signature>
						</view>
					</view>

					<view class="popup-bottom">
						<view class="btn1 btnBoxView" @tap="clearClick"
							>重签</view
						>

						<view class="btn2 btnBoxView" @tap="overSign"
							>完成签名并提交</view
						>
					</view>
				</view>
			</uni-popup>
		</view>

		<view v-if="processType && active === 1" class="warning-container">
			请到电脑端发起提交
		</view>
	</view>
</template>

<script>
import {
	getModelById,
	getUserDepts,
	getInstanceFormData,
	startProcess,
	startProcessWithAssociateForm,
} from '@/subPackagesIndex/pages/index/approval/launch/apis/design.js'

import { invoiceTotalAmountAndVerify } from '@/subPackagesIndex/pages/index/approval/launch/apis/reimbursement.js'

import FormRender from './forms/FormRender.vue'

import Process from './forms/Process.vue'

import diyNavTab from '@/subPackagesIndex/components/diy-navTab/diy-navTab.vue'
import processProgress from '@/subPackagesIndex/pages/index/approval/mainSub/components/processProgress.vue'
import associateForm from '../mainSub/components/associateForm.vue'
import approveItem from '@/subPackagesIndex/components/approve-item/approve-item.vue'
export default {
	components: {
		FormRender,
		Process,
		diyNavTab,
		processProgress,
		approveItem,
		associateForm,
	},

	data() {
		return {
			noClick: true,

			code: '',

			instanceId: '',

			formData: {},

			userDepts: [],

			userDeptId: '',

			processUsers: {},

			loading: false,

			form: {
				formId: '',

				formName: '',

				logo: {},

				formItems: [],

				process: {},

				remark: '',
			},

			isShowSignature: false,

			penColor: 'balck',

			penSize: 10,

			signatrueUrl: '',

			openSmooth: true,

			signatureObj: {},

			isClickSumbit: false,

			active: 1,

			tabList: [
				{ value: 1, text: '发起提交' },

				{ value: 2, text: '历史提交' },
			],

			instanceData: null,

			processList: null,

			multifunctionalParam: '',

			dataList: [],

			pageSize: 10,

			pageNo: 1,

			isAssociateFormMode: false,

			associateFormMode: '',

			associateFormTitle: '',

			associateFormTransientId: '',

			associateFormData: [],

			processType: '',

			loadingSumbit: false,

			invoiceUnable: 0, // 发票不可使用时 处于的状态： 1,2 ;
		}
	},

	onUnload() {
		// uni.setStorageSync('formData', this.formData)
		// uni.setStorageSync('code', this.code)
	},

	onLoad(options) {
		this.active = options.active

		this.processType = options.processType

		this.$store.commit('setResetting')

		this.code = options.code

		this.instanceId = options.instanceId

		this.instanceData = options.instanceData
			? JSON.parse(decodeURIComponent(options.instanceData))
			: null

		this.processList = options.processList
			? JSON.parse(decodeURIComponent(options.processList))
			: null

		if (this.$isNotEmpty(this.code)) {
			this.getUserDept()

			this.loadFormInfo(this.code)
		} else {
			console.log('参数缺失')
		}

		//

		if (options.isAssociateForm) {
			const formData = uni.getStorageSync('_associateFormData')

			if (formData) {
				this.isAssociateFormMode = true

				this.associateFormTitle = formData.title

				this.associateFormData = formData.data

				this.associateFormTransientId = formData.transientId
			}
		}

		if (this.active == 2) {
			this.getHistoryData()
		}
	},

	computed: {
		forms() {
			return this.$store.state.design.formItems
		},

		process() {
			return this.$store.state.design.process
		},
	},

	onReachBottom() {
		if (this.hasMore && this.active === 2) {
			this.pageNo = this.pageNo + 1

			this.getHistoryData()
		}
	},

	methods: {
		serachInput(val) {
			this.pageNo = 1

			this.dataList = []

			this.multifunctionalParam = val

			this.getHistoryData()
		},

		changeTab(value) {
			this.active = Number(value)

			if (value === 2) {
				this.pageNo = 1

				this.dataList = []

				this.getHistoryData()
			}
		},

		getHistoryData() {
			uni.showLoading({
				title: '加载中...',
			})

			this.$request
				.request(
					'wflow/wflow/smallProgram/process/task/getHistoricalSubmit',
					{
						method: 'post',

						data: {
							multifunctionalParam: this.multifunctionalParam,

							formId: this.form.formId || this.code,

							pageNo: this.pageNo,

							pageSize: this.pageSize,
						},
					}
				)
				.then((res) => {
					uni.hideLoading()

					if (res.records && res.records.length > 0) {
						this.dataList = this.dataList.concat(res.records)

						this.hasMore = true
					} else {
						this.hasMore = false
					}
				})
		},

		setSingure(value) {
			this.signatureObj = value

			this.openSignature()
		},

		clearClick() {
			this.$refs.signatureRef.clear()
		},

		overSign: function () {
			this.$refs.signatureRef.canvasToTempFilePath({
				success: (res) => {
					// 是否为空画板 无签名

					// 生成图片的临时路径

					// H5 生成的是base64

					// this.url = res.tempFilePath

					// 将图片保存至阿里云

					uni.uploadFile({
						url:
							getApp().globalData.uploadDomain +
							'oss-web/oss/upload/file?asyn=false',

						filePath: res.tempFilePath,

						name: 'file',

						header: {
							tenantId: uni.getStorageSync('orgId'),

							Authorization: uni.getStorageSync('token'),

							reqChannel: getApp().globalData.reqChannel,
						},

						success: (uploadFileRes) => {
							let data = JSON.parse(uploadFileRes.data).data

							let imgData = {
								...data,
							}

							if (imgData.url) {
								this.signatrueUrl = imgData.url

								if (this.signatureObj.name) {
									let arr = this.signatureObj.columnValue

									let obj = arr[this.signatureObj.index]

									arr[this.signatureObj.index] = {
										...obj,

										[this.signatureObj.id]:
											this.signatrueUrl,
									}

									this.formData = {
										...this.formData,

										...{
											[this.signatureObj.tableId]: {
												...arr,
											},
										},
									}
								} else {
									const obj = {
										[this.signatureObj.id]:
											this.signatrueUrl,
									}

									this.formData = {
										...this.formData,

										...obj,
									}
								}

								this.closeSignature()
							} else {
								this.closeSignature()

								uni.showToast({
									title: '签名提交失败~',

									icon: 'error',
								})
							}
						},

						fail() {
							this.closeSignature()

							uni.showToast({
								title: '签名提交失败~',

								icon: 'error',
							})
						},
					})
				},
			})
		},

		closeSignature() {
			this.isShowSignature = false

			this.$refs.signature.close()
		},

		//打开签字

		openSignature() {
			this.isShowSignature = true

			this.$refs.signature.open('bottom')
		},

		getFormValue(val) {
			this.formData = val
		},

		getUserDept() {
			getUserDepts(uni.getStorageSync('userId'))
				.then((rsp) => {
					this.userDepts = rsp

					if (this.userDepts.length > 0) {
						this.userDeptId = this.userDepts[0].id
					}
				})

				.catch((err) => {
					uni.showModal({
						title: '提示',

						content: '获取用户部门信息失败',
					})
				})
		},

		loadFormInfo(formId) {
			this.loading = true

			uni.showLoading({
				title: '加载中...',
			})

			getModelById(formId).then((rsp) => {
				uni.hideLoading()

				this.loading = false

				let form = rsp

				form.logo = JSON.parse(form.logo)

				this.form = form

				//构建表单及校验规则

				this.$store.state.design = form

				// if(uni.getStorageSync('code') === this.code && uni.getStorageSync('formData')) {

				// 	this.formData = uni.getStorageSync('formData')

				// }

				this.loadFormData()
			})

			// .catch((err) => {

			//   this.loading = false;

			//   uni.hideLoading();

			//   uni.showModal({

			//     title: "提示",

			//     content: "获取流程模型失败",

			//   });

			// });
		},

		loadFormData() {
			let instanceId = this.instanceId

			if (this.$isNotEmpty(instanceId)) {
				getInstanceFormData(instanceId)
					.then((rsp) => {
						this.formData = rsp
					})

					.catch((e) => {
						uni.showModal({
							title: '提示',

							content: '回显数据失败',
						})
					})
			} else {
				if (this.isAssociateFormMode) {
					const findFirst = this.form.formItems.find(
						(item) =>
							item.name === 'FileUpload' ||
							item.name === 'TJGJ_YY2'
					)

					const data = uni.getStorageSync('_associateFormData')

					// console.log('set file value')

					if (findFirst && data && data.resource) {
						this.formData = {
							[findFirst.id]: [data.resource],
						}
					}
				}
			}
		},

		getInvoiceSatus(list) {
			let status = 0 //什么都没有

			// 循环所有发票，只有有一张已使用，优先提示已使用 不再继续循环

			for (let i = 0; i < list.length; ++i) {
				const item = list[i]?.tags

				// tags 新逻辑

				// [] ： 什么都没验出来

				// ['验真成功']

				// ['验真成功','发票已使用']

				// ['验真失败','发票已使用'] and so on

				for (let j = 0; j < item.length; ++j) {
					if (item[j].indexOf('发票已使用') >= 0) {
						// 发票已使用

						status = 1

						break
					} else if (item[j].indexOf('验真失败') >= 0) {
						// 验真失败

						status = 2
					}
				}

				if (status == 1) {
					break
				}
			}

			this.invoiceUnable = status
		},

		async sumbit() {
			this.isClickSumbit = true

			let extraData = {}

			if (Reflect.has(this.$refs.form.$refs, 'sealset')) {
				const result = this.$refs.form.$refs.sealset[0].result

				if (
					result &&
					Object.keys(result).length &&
					Object.values(result).every(Boolean)
				) {
					extraData = result
				} else {
					uni.showToast({
						title: '请完善表单~',

						icon: 'none',
					})

					return
				}
			}

			this.formData = { ...this.formData, ...extraData }

			const newFormData = JSON.parse(JSON.stringify(this.formData))

			if (Object.keys(newFormData).length === 0) {
				console.log('newFormData', newFormData)

				uni.showToast({
					title: '请完善表单~',

					icon: 'none',
				})

				return
			}

			if (!this.$isNotEmpty(this.form.processDefId)) {
				uni.showToast({
					title: '流程未发布~',

					icon: 'none',
				})

				return
			}

			let warnString = ''

			this.forms.forEach((item) => {
				console.log(item)

				if (
					(!Object.prototype.hasOwnProperty.call(
						newFormData,
						item.id
					) ||
						newFormData[item.id] === '' ||
						(newFormData[item.id] &&
							newFormData[item.id].length === 0)) &&
					item.props?.required &&
					item.name !== 'TableList' &&
					item.name !== 'TJGJ_YY' &&
					item.name !== 'AssociateForm'
				) {
					console.log('s1', newFormData, item)

					warnString = 1
				}

				if (item.name === 'TableList') {
					console.log('s2')

					item.props.columns.forEach((columnsItem) => {
						if (
							!newFormData[item.id] &&
							columnsItem.props.required
						) {
							warnString = 1
						}

						if (
							newFormData[item.id] &&
							Object.values(newFormData[item.id]).length > 0
						) {
							Object.values(newFormData[item.id]).forEach((i) => {
								if (
									columnsItem.props.required &&
									(i[columnsItem.id] === null ||
										(i[columnsItem.id] &&
											i[columnsItem.id].length === 0) ||
										!Object.prototype.hasOwnProperty.call(
											i,
											columnsItem.id
										) ||
										i[columnsItem.id] === '')
								) {
									warnString = 1
								}
							})
						}
					})
				} else if (item.name === 'TJGJ_YY') {
					const result = Object.keys(this.formData)
						.filter((item) => /#/.test(item))
						.every((item1) => this.formData[item1])

					if (!result) {
						warnString = 1
					}
				}
			})

			if (warnString) {
				console.log('warnString', warnString)

				uni.showToast({
					title: '请完善表单~',

					icon: 'none',
				})

				return
			}

			let timeWarning = ''

			let dataTimeWarning = ''

			this.forms.forEach((item) => {
				if (item.name === 'TimeRangePicker' && newFormData[item.id]) {
					const arr = newFormData[item.id]

					if (!arr[0]) {
						timeWarning = '请选择开始时间~'
					} else if (!arr[1]) {
						timeWarning = '请选择结束时间~'
					} else if (
						arr[0].replace(':', '') > arr[1].replace(':', '')
					) {
						timeWarning = '结束时间不能小于开始时间~'
					}
				} else if (
					item.name === 'DateTimeRange' &&
					newFormData[item.id]
				) {
					const arr = newFormData[item.id]

					if (!arr[0]) {
						dataTimeWarning = '请选择开始日期时间~'
					} else if (!arr[1]) {
						dataTimeWarning = '请选择结束日期时间~'
					} else if (
						new Date(arr[0]).getTime() > new Date(arr[1]).getTime()
					) {
						dataTimeWarning = '结束日期时间不能小于开始日期时间~'
					}
				} else if (item.name === 'TableList') {
					item.props.columns.forEach((columnsItem) => {
						if (
							newFormData[item.id] &&
							Object.values(newFormData[item.id]).length > 0
						) {
							Object.values(newFormData[item.id]).forEach((i) => {
								if (
									columnsItem.name === 'TimeRangePicker' &&
									i[columnsItem.id] &&
									i[columnsItem.id].length > 0
								) {
									const arr = i[columnsItem.id]

									if (!arr[0]) {
										timeWarning = '请选择开始时间~'
									} else if (!arr[1]) {
										timeWarning = '请选择结束时间~'
									} else if (
										arr[0].replace(':', '') >
										arr[1].replace(':', '')
									) {
										timeWarning =
											'结束时间不能小于开始时间~'
									}
								} else if (
									columnsItem.name === 'DateTimeRange' &&
									i[columnsItem.id] &&
									i[columnsItem.id].length > 0
								) {
									const arr = i[columnsItem.id]

									if (!arr[0]) {
										dataTimeWarning = '请选择开始日期时间~'
									} else if (!arr[1]) {
										dataTimeWarning = '请选择结束日期时间~'
									} else if (
										new Date(arr[0]).getTime() >
										new Date(arr[1]).getTime()
									) {
										dataTimeWarning =
											'结束日期时间不能小于开始日期时间~'
									}
								}
							})
						}
					})
				}
			})

			if (timeWarning) {
				uni.showToast({
					title: timeWarning,

					icon: 'none',
				})

				return
			}

			if (dataTimeWarning) {
				uni.showToast({
					title: dataTimeWarning,

					icon: 'none',
				})

				return
			}

			let sealUploadWarning = ''

			this.forms.forEach((item) => {
				if (item.name === 'FileUpload' && item.props.userSeal) {
					newFormData[item.id].forEach((i) => {
						if (!i.isfinshed) {
							sealUploadWarning = 1
						}
					})
				} else if (item.name === 'TableList') {
					item.props.columns.forEach((columnsItem) => {
						if (
							newFormData[item.id] &&
							Object.values(newFormData[item.id]).length > 0
						) {
							Object.values(newFormData[item.id]).forEach((i) => {
								if (
									columnsItem.name === 'FileUpload' &&
									columnsItem.props.userSeal
								) {
									if (
										i[columnsItem.id] &&
										i[columnsItem.id].length > 0
									) {
										i[columnsItem.id].forEach((inx) => {
											if (!inx.isfinshed) {
												sealUploadWarning = 1
											}
										})
									}
								}
							})
						}
					})
				}
			})

			if (sealUploadWarning) {
				uni.showToast({
					title: '请将印章信息填写完整',

					icon: 'none',
				})

				return
			}

			if (this.loadingSumbit) {
				return false
			}

			this.loadingSumbit = true

			if (this.instanceData) {
				const rootTasks = this.processList.filter(
					(i) => i.nodeType === 'ROOT' && !i.result
				)

				let parmas = {
					instanceId: this.instanceId,

					taskId: rootTasks[rootTasks.length - 1].taskId,

					formData: this.formData,

					action: 'reCommit',
				}

				this.$request
					.request('wflow/wflow/process/task/handler', {
						method: 'post',

						data: {
							...parmas,
						},
					})
					.then(() => {
						this.loadingSumbit = false

						uni.showToast({
							title: '处理任务成功',

							icon: 'success',
						})

						setTimeout(function () {
							uni.navigateBack({
								delta: 1,
							})
						}, 0)
					})
					.catch((err) => {
						this.loadingSumbit = false

						uni.showToast({
							title: '处理任务失败',

							icon: 'error',
						})
					})

				return false
			}

			let startParams = {
				deptId: this.userDeptId,

				formData: this.formData,

				processUsers: this.processUsers,
			}

			let isDetail = this.$store.state.isDetail

			if (isDetail) {
				let type = this.$store.state.invoiceInfo.type

				let parentId = this.$store.state.invoiceInfo.parentId

				let totalAmount = this.$store.state.invoiceInfo.totalAmount

				let varifyInvoiceDTOList = this.getDtoList(
					this.$store.state.billList[this.$store.state.cwId]
				)

				let timeAreaId = this.$store.state.timeAreaId

				let formData = this.$store.state.formData

				let time = formData[timeAreaId]

				let begin = ''

				let end = ''

				if (time && time[0] !== '' && time[1] !== '') {
					begin = time[0]

					end = time[1]
				}

				let res = await invoiceTotalAmountAndVerify({
					type,

					parentId,

					totalAmount,

					varifyInvoiceDTOList,

					begin,

					end,
				})

				this.loadingSumbit = false

				let data = res.data

				let varifyInvoiceVOList = data.varifyInvoiceVOList
					? data.varifyInvoiceVOList
					: []

				let newVolist = []

				varifyInvoiceVOList.forEach((item) => {
					if (item.tags && item.tags.length > 0) {
						newVolist.push(item)
					}
				})

				this.$store.commit('setVarifyInvoiceVOList', newVolist)

				let selectId = []

				varifyInvoiceVOList.forEach((item) => {
					selectId.push(item.id)
					// 发票不可用状态 0:tags没返回值 1:发票已使用,2 验真失败
					this.getInvoiceSatus(varifyInvoiceVOList)
				})

				if (data.overAmount) {
					uni.showModal({
						title: '',

						showCancel: false,

						content: '报销金额大于设定报销类目金额',

						confirmText: '知道了',

						success: function () {},
					})

					return
				} else {
					if (this.invoiceUnable === 1) {
						uni.showModal({
							title: '',

							showCancel: false,

							content:
								'发票已使用：发票在其他审批单中已被使用，请提交其他发票',

							confirmText: '知道了',

							success: function () {},
						})

						return
					} else if (this.invoiceUnable === 2) {
						uni.showModal({
							title: '',

							showCancel: false,

							content:
								'报销凭证验真失败，请前往报销明细检查报销凭证',

							confirmText: '知道了',

							success: function () {},
						})

						return
					} else {
						let newVal = []

						let obj = JSON.parse(
							JSON.stringify(
								startParams.formData[this.$store.state.cwId]
							)
						)

						obj.forEach((item) => {
							let threeObj = item.threeObj

							for (let key in threeObj) {
								let fileList = threeObj[key].fileList

								fileList.forEach((list, inx) => {
									let selectIndex = selectId.indexOf(list.id)

									if (selectIndex > -1) {
										threeObj[key].fileList[inx] = {
											...list,

											tags: varifyInvoiceVOList[
												selectIndex
											].tags,
										}
									}
								})
							}

							newVal.push(threeObj)
						})

						this.$set(
							startParams.formData,
							this.$store.state.cwId,
							obj
						)
					}
				}
			}

			if (this.isAssociateFormMode) {
				startProcessWithAssociateForm({
					...startParams,

					transientId: this.associateFormTransientId,
				}).then((rsp) => {
					if (rsp) {
						uni.showToast({
							title: '提交成功~',

							icon: 'success',
						})

						const pages = getCurrentPages()

						if (pages.length > 1) {
							setTimeout(() => {
								uni.navigateBack({
									delta: 1,
								})
							}, 1000)
						} else {
							setTimeout(() => {
								uni.redirectTo({
									url: '/subPackagesForm/pages/index/index?tab=2',
								})
							}, 1000)
						}
					}
				})

				return
			}

			startProcess(this.form.processDefId, startParams).then((rsp) => {
				if (rsp) {
					this.loadingSumbit = false

					uni.showToast({
						title: '提交成功~',

						icon: 'success',
					})

					setTimeout(() => {
						uni.navigateBack({
							delta: 1,
						})
					}, 0)
				}
			})
		},

		getDtoList(list) {
			let dtoList = []

			list.forEach((item) => {
				let threeObj = item.threeObj

				for (let key in threeObj) {
					let fileList = threeObj[key].fileList

					dtoList = [...dtoList, ...fileList]
				}
			})

			return dtoList
		},
	},

	watch: {
		formData(val) {
			this.$store.commit('setFormData', val)
		},
	},
}
</script>

<style scoped lang="scss">
.container {
	padding: 0;

	padding-top: 100rpx;
}

.btnBoxView {
	width: 50%;

	text-align: center;

	height: 50px;

	line-height: 50px;

	color: #ffffff;
}

.btnBoxView:active {
	background-color: #cccccc;

	color: #333333;
}

.btn1 {
	background-color: #ff8f58;
}

.btn2 {
	background-color: $primary-color;
}

/deep/ .uni-file-picker__lists {
	display: none !important;
}

/deep/ .file-count {
	display: none !important;
}

/deep/ .uni-popup .uni-popup__wrapper {
	border-radius: 20rpx !important;
}

.popup-content {
	overflow-y: auto !important;
}

.serach-fixed {
	position: fixed;

	padding: 20rpx 0;

	border-top: 2rpx solid #efefef;

	width: 100%;

	background: #fff;

	z-index: 2;
}

/deep/ .serach-box {
	margin: 0 10rpx;
}

.data-container {
	padding: 0rpx 20rpx 20rpx 20rpx;
}

/deep/ .uni-forms-item {
	margin-bottom: 0 !important;
}

.item-container {
	background: #fff;

	padding: 20rpx;

	margin: 20rpx 0;

	border-radius: 8rpx;
}

.warning-container {
	display: flex;

	justify-content: center;

	margin-top: 120rpx;

	color: #6c6c6c;

	font-size: 32rpx;
}
</style>
